import { Injectable } from '@nestjs/common';
import { FetchService } from './fetch.service';
import { ILocation } from '../interfaces/location.interface';
import { IPosition } from '../interfaces/position.interface';
import { IDistance } from '../interfaces/distance.interface';

@Injectable()
export class PositionService {

  constructor(private readonly fetchService: FetchService) { }

  // 通过 geohash 获取精确地址
  async getPositionForGeohash(geohash): Promise<IPosition> {

    const locationArr = geohash.split(',');

    const res = await this.fetchService.getPositionByTencent(locationArr[0], locationArr[1]);
    let addressInfo: IPosition = null;

    if (res.data.status === 0) {
      const { address, formatted_addresses, address_component } = res.data.result;
      addressInfo = {
        name: formatted_addresses.recommend,
        address,
        city: address_component.province,
        latitude: locationArr[0],
        longitude: locationArr[1],
        geohash
      };
    }

    return addressInfo;
  }

  // 通过关键字搜索地址
  async searchPlace(keyword, cityName): Promise<IPosition[]> {

    const res = await this.fetchService.searchPlaceForKeywordByTencent(keyword, cityName);
    let cityList: IPosition[] = [];

    if (res.data.status === 0) {
      for (const value of res.data.data.values()) {
        const { title, address, location } = value;
        cityList.push({
          name: title,
          address,
          latitude: location.lat,
          longitude: location.lng,
          geohash: `${location.lat},${location.lng}`
        });
      }
    }

    return cityList;
  }

  // 通过 ip 地址定位
  async getLocationForIp(req): Promise<ILocation> {

    let ip = '180.158.102.141';
    if (process.env.NODE_ENV !== 'development') {
      ip = req.ip;
    }

    let res = await this.fetchService.getLocationForIpByTencent(ip);
    let cityInfo: ILocation = null;
    let lat, lng, city;

    if (res.data.status === 0) {
      const { location, ad_info } = res.data.result;
      lat = location.lat;
      lng = location.lng;
      city = ad_info.city;
    } else {
      res = await this.fetchService.getLocationForIpByBaidu(ip);
      if (res.data.status === 0) {
        const { point, address } = res.data.result;
        lat = point.y;
        lng = point.x;
        city = address;
      }
    }

    cityInfo = {
      lat,
      lng,
      city: city.replace(/市$/, '')
    };

    return cityInfo;
  }

  // 获取骑行距离和时间
  async getDistanceForRiding(from, to): Promise<IDistance> {

    const res = await this.fetchService.getDistanceForRiding(from, to);
    let riding: IDistance = null;

    if (res.data.status === 0) {
      const { distance, duration } = res.data.result;
      riding = {
        distance,
        duration
      };
    }

    return riding;
  }

}